package com.zmx.doctor.view.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.OrderItemAdapter;
import com.zmx.doctor.fragment.ThreeFragment;
import com.zmx.doctor.fragment.wenzhen.GraphicPhysicianFragment;
import com.zmx.doctor.fragment.wenzhen.PrescribingPhysicianFragment;
import com.zmx.doctor.fragment.wenzhen.VoicePhysicianFragment;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.PatientOrder;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PhysicianListActivity extends BaseActivity {

    private RecyclerView reView;
    private SmartRefreshLayout refreshLayout;
    private OrderItemAdapter adapter;
    private List<PatientOrder> lists;

    private View mEmptyLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_physician_list;
    }

    @Override
    protected void initViews() {

        setToolbar(R.id.tool_bar);
        mEmptyLayout = findViewById(R.id.empty);
        reView = findViewById(R.id.reView);
        reView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new OrderItemAdapter(mActivity);
        reView.setAdapter(adapter);
        lists = new ArrayList<>();
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent(mActivity, OrderDetailsActivity.class);
                intent.putExtra("ask_id", lists.get(listPosition).getId() + "");
                intent.putExtra("type", "1");
                intent.putExtra("patient_id", lists.get(listPosition).getPatient_id() + "");
                startActivity(intent);

            }
        });

        // 开启自动加载功能
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {

            getData();

        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            handler.sendEmptyMessage(3);

        });

        //触发自动刷新
        refreshLayout.autoRefresh();

    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    lists.clear();
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1) {

                            JSONArray array = new JSONArray(object.getString("data"));
                            Gson gson = new Gson();
                            for (int i = 0; i < array.length(); i++) {

                                JSONObject jsonObject = array.getJSONObject(i);
                                PatientOrder order = gson.fromJson(jsonObject.toString(), PatientOrder.class);
                                lists.add(order);

                            }

                            adapter.setListAndNotifyDataSetChanged(lists);//就是设置list然后刷新


                        }else if(object.getInt("code") == -1){

                            new AlertDialog.Builder(mActivity)
                                    .setTitle("温馨提示")
                                    .setMessage("该账户未认证，请先认证")
                                    .setPositiveButton("确定",(dialogInterface, i) -> {

                                        Intent intent = new Intent();
                                        intent.setClass(mActivity, DoctorCertifiedActivity.class);
                                        startActivity(intent);

                                    })
                                    .show().setCancelable(true);

                        }

                        if (lists.size() > 0) {

                            mEmptyLayout.setVisibility(View.GONE);

                        } else {

                            mEmptyLayout.setVisibility(View.VISIBLE);

                        }
                        //刷新加载
                        refreshLayout.finishRefresh(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 3:
                    //刷新加载
                    refreshLayout.finishLoadMore(true);

                    break;
            }
        }
    };

    /**
     * 获取所有提问
     */
    public void getData() {

        List<String> ls = new ArrayList<>();
        ls.add("100");
        ls.add("1");
        ls.add("1");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "askList");
        params.put("data[type]", "1");
        params.put("data[row]", "1");
        params.put("data[number]", "100");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 1, 404);

    }

//    static final int NUM_ITEMS = 3;
//    private List<Fragment> fragmentList = new ArrayList<Fragment>();
//    private String[] strings = new String[]{"图文问诊","电话问诊","开药问诊"};
//
//    @Override
//    protected int getLayoutId() {
//        return R.layout.activity_physician_list;
//    }
//
//    @Override
//    protected void initViews() {
//
//        setToolbar(R.id.tool_bar);
//        fragmentList.add(new GraphicPhysicianFragment());
//        fragmentList.add(new PrescribingPhysicianFragment());
//        fragmentList.add(new VoicePhysicianFragment());
//
//        TabLayout tab_layout = findViewById(R.id.tab_layout);
//        ViewPager viewPager = findViewById(R.id.viewPager);
//        PhysicianListActivity.MyAdapter fragmentAdater = new PhysicianListActivity.MyAdapter(getSupportFragmentManager());
//        viewPager.setAdapter(fragmentAdater);
//        tab_layout.setupWithViewPager(viewPager);
//
//    }
//
//    public class MyAdapter extends FragmentPagerAdapter {
//        public MyAdapter(FragmentManager fm) {
//            super(fm);
//        }
//
//        @Override
//        public int getCount() {
//            return NUM_ITEMS;
//        }
//
//        @Override
//        public Fragment getItem(int position) {
//            return fragmentList.get(position);
//        }
//
//        @Nullable
//        @Override
//        public CharSequence getPageTitle(int position) {
//            return strings[position];
//        }
//    }

}
